import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.DateFormatter;

import cmpe273.classproject.server.dto.MovieResponse;
import cmpe273.classproject.server.dto.PersonResponse;
import cmpe273.classproject.server.model.Movie;
import cmpe273.classproject.server.model.Person;
import cmpe273.classproject.server.model.RentalTransaction;
import cmpe273.classproject.server.service.MovieServiceImplProxy;

public class SimpleCustomer extends javax.swing.JFrame {

    /** Creates new form SimpleCustomer */
    public SimpleCustomer() {
        initComponents();
    }
    
     public SimpleCustomer(AllSimple ui) {
        allSimple = ui;
        initComponents();
    }
     
     public SimpleCustomer(AllMovies ui) {
     	allMovies = ui;
         initComponents();
     }
     
     

     public int memberID;
     public String name;
     public String address;
     public String balance;
     public AllMovies allMovies;
     public Bill bill;
     
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jLabel6 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jTextField4 = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jTextField5 = new javax.swing.JTextField();
        jTextField3 = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jTextField2 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jTextField6 = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        btnIssueMovie = new javax.swing.JButton();
        btnReturnMovie = new javax.swing.JButton();
        btnGenerateBill = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel6.setText("Issued Movies");

        jLabel5.setText("Subscription Fee");

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "S. No.", "Movie Name", "Rented On", "Charge"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.Object.class, java.lang.Integer.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jLabel4.setText("Membership No.");

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12));
        jLabel1.setText("Simple Member Details");

        jLabel2.setText("Name");

        jLabel3.setText("Address");

        jLabel7.setText("Balance");

        jLabel8.setText("$");

        jButton1.setText("Back");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Save");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        
        btnIssueMovie.setText("Issue Movie");
        btnIssueMovie.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	btnIssueMovieActionPerformed(evt);
            }
        });
        
        btnGenerateBill.setText("Generate Bill");
        btnGenerateBill.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGenerateBillActionPerformed(evt);
            }
        });
        
        btnReturnMovie.setText("Return Movie");
        btnReturnMovie.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	btnReturnMovieActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(28, 28, 28)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4))
                        .addGap(36, 36, 36)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 270, Short.MAX_VALUE)
                            .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 270, Short.MAX_VALUE)
                            .addComponent(jTextField3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 270, Short.MAX_VALUE)
                            .addComponent(jTextField4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 270, Short.MAX_VALUE)))
                    .addComponent(jLabel6)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel7)
                                .addGap(38, 38, 38)
                                .addComponent(jLabel8))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(8, 8, 8)
                                .addComponent(btnIssueMovie, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(btnReturnMovie, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jTextField6, javax.swing.GroupLayout.DEFAULT_SIZE, 267, Short.MAX_VALUE)))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(btnGenerateBill, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(32, 32, 32)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(8, 8, 8)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(42, 42, 42)
                        .addComponent(jLabel6))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(btnGenerateBill)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7)
                    .addComponent(jLabel8))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2)
                    .addComponent(btnReturnMovie)
                    .addComponent(btnIssueMovie))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        
        pack();
    }// </editor-fold>

    public void loadMember()
    {
    	jTextField1.setText(name);
    	jTextField2.setText(address);
    	jTextField4.setText(String.valueOf(memberID));
    	jTextField4.setEditable(false);
    	jTextField6.setText(balance);
    	jTextField6.setEditable(false);
    	loadMovies();
    }
    
    private void btnGenerateBillActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    	
    	//Person person = new Person();
    	//person.setMemberId(memberID);
    	
    	if (bill == null)
        {
            bill = new Bill(memberID);
        }
    
    	bill.setVisible(true);
    	//this.setVisible(false);
    }
    
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        if (allSimple == null)
            {
                allSimple = new AllSimple(this);
            }
        
        allSimple.setVisible(true);
        this.setVisible(false); 
    }

    public void loadMovies()
    {
        String movieId, movieName, releaseDate, rentAmount, totalCopies;
        String[] columns = new String[]{"MovieID", "Movie Name", "Due Date", "Rent Amount", "Outstanding"};        
        DefaultTableModel modal = new DefaultTableModel(new String[][]{}, columns);
        
                   
        List<Movie> movies = getAllMoviesForCustomer();
        
        if (movies.size() > 0)
        {
                            
            for(int i=0; i< movies.size(); i++)
            {
                Movie movie = movies.get(i);                   
                movieId = String.valueOf(movie.getMovieId());
                movieName = movie.getMovieName();
                DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                java.util.Date dt = new java.util.Date(movie.getReleaseDate().getTimeInMillis());
                releaseDate = df.format(dt);                    
                rentAmount = String.valueOf(movie.getRentAmount());
                totalCopies = String.valueOf(movie.getTotalCopies());
                
                modal.addRow(new String[]{movieId, movieName, releaseDate, rentAmount, totalCopies});
            }
        }
        
        
        jTable1.setModel(modal);
        
    }
    
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    	
    	updatePerson(memberID, jTextField1.getText(), jTextField2.getText());    	
        
    	allSimple.dispose();
    	allSimple = null;
    	
        if (allSimple == null) {
            allSimple = new AllSimple(this);
        }
        
        allSimple.setVisible(true);
        this.setVisible(false);
}
    
    private void btnIssueMovieActionPerformed(java.awt.event.ActionEvent evt) {
    
    	if (allMovies == null)
        {
   		 allMovies = new AllMovies(this);
        }
    
   	 allMovies.bPremium = false;
   	 allMovies.bIssueMovie = true;
   	 allMovies.memberId = memberID;
   	 allMovies.loadControls();
   	 allMovies.setVisible(true);
   	
    }

    private void btnReturnMovieActionPerformed(java.awt.event.ActionEvent evt) {
    	
    	if (jTable1.getSelectedRow() < 0)
        {
            JOptionPane.showMessageDialog(this, "Please select member to view member's details.");
            return;
        }
    	
    	int iSelectedRow = jTable1.getSelectedRow();
        int movieId = Integer.parseInt(jTable1.getValueAt(iSelectedRow, 0).toString());
      
        returnMovie(memberID, movieId);
        
        loadMovies();
        
    }
 
    public AllSimple allSimple = null; 
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new SimpleCustomer().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JButton btnGenerateBill;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton btnIssueMovie;
    private javax.swing.JButton btnReturnMovie;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    private javax.swing.JTextField jTextField5;
    private javax.swing.JTextField jTextField6;
    // End of variables declaration
    
    private List<Movie> getAllMoviesForCustomer()
    {
    	try
    	{
    		MovieServiceImplProxy proxy = new MovieServiceImplProxy();
    		Movie[] movies = proxy.getAllMoviesByPerson(memberID).getMovies();
    		
    		List<Movie> lst = new ArrayList<Movie>();
    		
    		if (movies != null)
    			lst = Arrays.asList(movies);
    		return lst;
    	}
    	catch(Exception ex)
    	{
    		ex.printStackTrace();
    	}
    	
    	return null;
    }
    
    private PersonResponse updatePerson(int memberID, String name, String address)
    {
    	try
    	{
    		Person person = new Person();
    		person.setMemberId(memberID);
    		person.setFirstName(name);
    		person.setAddress(address);
    		MovieServiceImplProxy proxy = new MovieServiceImplProxy();
    		PersonResponse personResponse = proxy.updatePerson(person);    		
    		return personResponse;
    	}
    	catch(Exception ex)
    	{
    		ex.printStackTrace();
    	}
    	
    	return null;
    }
    
    private MovieResponse returnMovie(int memberID, int movieID)
    {
    	try
    	{
    		RentalTransaction rent = new RentalTransaction();
    		rent.setMemberId(memberID);
    		rent.setMovieId(movieID);
    		
    		MovieServiceImplProxy proxy = new MovieServiceImplProxy();
    		MovieResponse movieResponse = proxy.submitMovie(rent); 
    		if (movieResponse.getError() == 0)
    		{
    			JOptionPane.showMessageDialog(this, "Movie Returned successfully.");
    		}
    		return movieResponse;
    	}
    	catch(Exception ex)
    	{
    		ex.printStackTrace();
    	}
    	
    	return null;
    }
}
